package dome_002;

/**
 * <p>Description: [synchronized关键字,对某个对象加锁]</p>
 * Created on 2020/12/3
 *
 * @author <a href="mailto: 819712047@qq.com">谢振东 </a>
 * @version 1.0
 */
public class Demo002_01 {

    private int count = 10;
    private Object object = new Object();

    public void test() {
        //任何线程要执行下面的代码，必须先拿到object对象的锁
        synchronized (object) {
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "已获取锁");
            count--;
            System.out.println(Thread.currentThread().getName() + " count = " + count);
        }
    }

    public static void main(String[] args) {
        Thread thread1 = new Thread(new SyncAddRunnable(null));
        Thread thread2 = new Thread(new SyncAddRunnable(null));

        thread1.setName("thread1");
        thread2.setName("thread2");

        thread1.start();
        thread2.start();

        Demo002_01 demo002_01 = new Demo002_01();

        Thread thread3 = new Thread(new SyncAddRunnable(demo002_01));
        Thread thread4 = new Thread(new SyncAddRunnable(demo002_01));

        thread3.setName("thread3");
        thread4.setName("thread4");

        thread3.start();
        thread4.start();
    }

    public static class SyncAddRunnable implements Runnable {

        Demo002_01 demo002_01;

        public SyncAddRunnable(Demo002_01 demo002_01) {
            this.demo002_01 = demo002_01;
        }

        @Override
        public void run() {
            System.out.println(String.format("运行线程开始-" + Thread.currentThread().getName()));
            if (demo002_01 == null) {
                demo002_01 = new Demo002_01();
            }
            demo002_01.test();
            System.out.println(String.format("运行线程结束-" + Thread.currentThread().getName()));
        }
    }
}
